<?php
/**
 * Created by PhpStorm.
 * User: ybjaa
 * Date: 2017/5/8
 * Time: 11:15
 */

namespace App\Business\Menu;


use App\Business\BusBase;
use App\Business\ReturnResult;
use App\Models\menus_manage;
use Illuminate\Support\Facades\DB;

class SortDownMenu extends BusBase
{

    public $ID;


    protected function Handle()
    {
        return $this->SortDownMenu();
    }

    public function GetBusinessName()
    {
        return "同级菜单中向下排序";
    }


    protected function SortDownMenu()
    {

        if(!$this->ID) return ReturnResult::Error(null,"参数无效");

        //开启事务
        DB::beginTransaction();

        //取节点
        $menu=menus_manage::find($this->ID);

        if(!$menu)
        {
            DB::rollBack();
            return ReturnResult::Error(null,"参数错误");
        }

        if(!$menu->nextID)
        {
            DB::rollBack();
            return ReturnResult::Error(null,"已是单层节点中的最后节点");
        }

        //检测下一节点
        $nextMenu=menus_manage::find($menu->nextID);


        if(!$nextMenu||$menu->parentID!==$nextMenu->parentID)
        {
            DB::rollBack();
            return ReturnResult::Error(null,"参数错误");
        }

        $nextID=$nextMenu->nextID;


        //检测上一节点
        $previousMenu=menus_manage::where("nextID",$menu->ID)->first();


        if($previousMenu&&$menu->parentID!==$previousMenu->parentID)
        {
            DB::rollBack();
            return ReturnResult::Error(null,"参数错误");
        }

        if($previousMenu)
        {
            $previousMenu->nextID=$nextMenu->ID;
            $previousMenu->save();
        }

        $nextMenu->nextID=$menu->ID;
        $nextMenu->save();

        $menu->nextID=$nextID;


        $menu->save();

        DB::commit();

        return ReturnResult::Success();











    }


}